﻿using System;
using System.Text.RegularExpressions;

namespace NOSDC.Services.Extensions
{
    public static class StringExtensions
    {
        /// <summary>
        /// Truncates a string to the desired length, also adds by default an ellipses at the end of the text
        /// </summary>
        /// <param name="val">The string</param>
        /// <param name="truncateLength">Length to trim the string to</param>
        /// <param name="truncateText">The text to place at the end of the string</param>
        public static string Truncate(this string val, int truncateLength = 100, string truncateText = "...")
        {
            if (!String.IsNullOrEmpty(val))
            {
                if (val.Length > truncateLength)
                {
                    val = val.Substring(0, truncateLength) + truncateText;
                }
            }

            return val;
        }

        /// <summary>
        /// Generates an SEO friendly url
        /// </summary>
        /// <param name="url">The url to seo friendly</param>
        /// <returns>A friendly url</returns>
        public static string ToSeoUrl(this string url)
        {
            string encodedUrl = (url ?? "").ToLower();
            encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");
            encodedUrl = encodedUrl.Replace("'", "");
            encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");
            encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");
            encodedUrl = encodedUrl.Trim('-');

            return encodedUrl;
        }

        /// <summary>
        /// Removes all HTML tags from a string
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string StripHTML(this string val)
        {
            return Regex.Replace(val, @"<(.|\n)*?>", String.Empty);
        }
    }
}
